package com.xz.knowledgeDuplication.util;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.CannedAccessControlList;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.joda.time.DateTime;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import java.io.InputStream;
import java.util.UUID;

/**
 * 文件帮助类
 *
 * @author 召
 * @date 2022-01-02 17:31:35
 */
@Data
@AllArgsConstructor
@NoArgsConstructor
public class FileUtil {

    private String endpoint;
    private String accessKeyId;
    private String accessSecret;
    private String bucketName;

    /**
     * 上传附件
     *
     * @param inputStream
     * @param module
     * @param originalFilename
     * @return
     */
    public String upload(InputStream inputStream, String module, String originalFilename) {

        //判断oss实例是否存在：如果不存在则创建，如果存在则获取
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessSecret);
        if (!ossClient.doesBucketExist(bucketName)) {
            //创建bucket
            ossClient.createBucket(bucketName);
            //设置oss实例的访问权限：公共读
            ossClient.setBucketAcl(bucketName, CannedAccessControlList.PublicRead);
        }

        //构建日期路径：avatar/2020/08/11/文件名
        String folder = new DateTime().toString("yyyy/MM/dd");

        //文件名：uuid.扩展名
        String fileName = UUID.randomUUID().toString();
        String fileExtension = originalFilename.substring(originalFilename.lastIndexOf("."));
        String key = module + "/" + folder + "/" + fileName + fileExtension;

        //文件上传至阿里云
        ossClient.putObject(bucketName, key, inputStream);

        // 关闭OSSClient。
        ossClient.shutdown();

        //返回url地址
        return "https://" + bucketName + "." + endpoint + "/" + key;

    }

    /**
     * 删除附件
     *
     * @param url
     */
    public void delete(String url) {
        //判断oss实例是否存在：如果不存在则创建，如果存在则获取
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessSecret);
        String objectName = url.replace("https://" + bucketName + "." + endpoint + "/", "");
        ossClient.deleteObject(bucketName, objectName);
        ossClient.shutdown();
    }

}
